<template>
  <BasicModal
    v-bind="$attrs"
    width="50%"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #params>
        <a-button type="primary" @click="handleCreateParam">新增</a-button>
        <BasicTable @register="registerTable">
          <template #action="{ record }">
            <TableAction
              :actions="[
                {
                  label: '删除',
                  color: 'error',
                  onClick: handleDel.bind(null, record),
                },
              ]"
            />
          </template>
        </BasicTable>
      </template>
      <template #dynSentence="{ model }">
        <a-button type="primary" @click="handleScript(model)"
          >配置grovvy脚本</a-button
        >
      </template>
    </BasicForm>
  </BasicModal>
  <EditScriptDrawer
    @register="registerScriptDrawer"
    @success="handleSetScript"
  />
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicModal, useModal, useModalInner } from '@/components/Modal';
import { BasicForm, useForm } from '@/components/Form/index';
import { formSchema } from './data';
import { useMessage } from '@/hooks/web/useMessage';
import { edit, add } from '@/api/sys/dev/reportDataSetManager';
import { editParams } from '@/api/sys/dev/reportDataSetManager';

import { useI18n } from '@/hooks/web/useI18n';
import {
  BasicTable,
  useTable,
  TableAction,
  EditRecordRow,
} from '@/components/Table';
// import EditParamModal from './EditParamModal.vue';
import { paramsList } from '@/api/sys/dev/reportDataSetManager';
import EditScriptDrawer from './EditScriptDrawer.vue';
import { useDrawer } from '@/components/Drawer';
const { t } = useI18n();
const emit = defineEmits(['success', 'register']);
let isUpdate = ref(true);
let dataSetRecord = {} as Recordable;
const { createMessage } = useMessage();

const [
  registerForm,
  { resetFields, setFieldsValue, getFieldsValue, validate },
] = useForm({
  labelWidth: 80,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 24 },
});
const currentEditKeyRef = ref('');
const params = ref<Recordable[]>([]);

const [registerTable, { insertTableDataRecord, deleteTableDataRecord, setTableData, getDataSource }] =
  useTable({
    dataSource: params.value,
    maxHeight: 200,
    columns: [
      {
        title: 'id',
        dataIndex: 'id',
        ifShow: false,
      },
      {
        title: '参数名',
        dataIndex: 'paramName',
        width: 150,
        editRow: true,
        editRule: async (text, record) => {
          if (!text) return '请输入参数名';
          const dataSource = getDataSource();
          const findExit = dataSource.filter(
            (d) => d.paramName === record.paramName
          );
          if (findExit && findExit.length > 1) {
            return '参数已经存在';
          }
          return '';
        },
        editComponent: 'Input',
      },
      {
        title: '必填',
        dataIndex: 'requiredFlag',
        width: 80,
        editRow: true,
        editRule: true,
        editComponent: 'ApiSelect',
        editComponentProps: {
          dictCode: 'yes_or_no',
        },
        editRender: ({ record }) => {
          return record.requiredFlagStr;
        },
      },
      {
        title: '参数类型',
        dataIndex: 'paramType',
        width: 130,
        editRow: true,
        editRule: true,
        editComponent: 'ApiSelect',
        editComponentProps: {
          dictCode: 'data_set_param_type',
        },
        editRender: ({ record }) => {
          return record.paramTypeStr;
        },
      },
      {
        title: '参数描述',
        dataIndex: 'paramDesc',
        editRow: true,
        editRule: true,
        editComponent: 'Input',
      },
    ],
    rowKey: 'id',
    useSearchForm: false,
    pagination: false,
    bordered: true,
    showIndexColumn: false,
    actionColumn: {
      width: 120,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: 'right',
    },
  });
const getParamList = async (setId) => {
  const res = (await paramsList(setId)) as unknown as Recordable[];
  params.value = res;
  res.forEach(r => r.editable = true)
  setTableData(res);
};
const [registerModal, { setModalProps, closeModal }] = useModalInner(
  async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    currentEditKeyRef.value = '';
    if (unref(isUpdate)) {
      dataSetRecord = data.record;
      await getParamList(dataSetRecord.id);
      setFieldsValue({
        ...data.record,
      });
    } else {
      setTableData([]);
      setFieldsValue({ setId: data.setId });
    }
  }
);
const getTitle = computed(() => (!unref(isUpdate) ? t('新增') : t('编辑')));

const [registerScriptDrawer, { openDrawer: openScriptDrawer }] = useDrawer();
const handleScript = (model: Recordable) => {
  console.log(model, 'mo');
  openScriptDrawer(true, {
    script: model.dynSentence,
    params: params.value,
    setHisId: model.id,
    setName: model.setName,
  });
};
const handleSetScript = (script: string) => {
  setFieldsValue({
    dynSentence: script,
  });
};
const handleDel = (record: Recordable) => {
  console.log(record, 'rere')
  deleteTableDataRecord(record.id)
}
const handleSave = async (record) => {
  currentEditKeyRef.value = '';
  const valid = await record.onValid?.();
  if (valid) {
    try {
      currentEditKeyRef.value = '';
      record.onEdit(false, true);
      if (record.id) {
        await editParams({ ...record, setId: dataSetRecord.id });
        createMessage.success('更新成功');
        getParamList(dataSetRecord.id);
      }
    } catch (error) {}
  }
};
const handleEditStart = (record: EditRecordRow) => {
  // 有当前正在编辑的行 不开启新的编辑行
  if (currentEditKeyRef.value) return;
  currentEditKeyRef.value = record.id;
  record.onEdit?.(true);
};

function handleCancel(record: EditRecordRow) {
  currentEditKeyRef.value = '';
  record.onEdit?.(false, false);
}
const check = (tableValues: any[]) => {
  const editableValues = tableValues.filter((t) => t.editable);
  if (editableValues.length) {
    createMessage.error('请先保存表格信息');
    return false;
  }
  return true;
};
async function handleSubmit() {
  try {
    const val = getFieldsValue();
    const { dynSentence } = val;
    if (!dynSentence) {
      createMessage.error('请配置脚本');
      return;
    }
    // if (!check(getDataSource())) return;
    const values = await validate();
    setModalProps({ confirmLoading: true });
    if (unref(isUpdate)) {
      await edit({ ...values, params: getDataSource(), scriptType: 'grovvy' });
      createMessage.success(t('修改成功'));
    } else {
      await add({ ...values, params: getDataSource(), scriptType: 'grovvy' });
      createMessage.success(t('保存成功'));
    }
    closeModal();
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
// function handleSuccess(opt: string, data: Recordable) {
//   const rows = getDataSource();
//   if (opt === 'add') {
//     if (rows.filter((d) => d.paramName === data.paramName).length > 0) {
//       createMessage.error('参数名重复');
//       return;
//     }
//     rows.push(data);
//     setTableData(rows);
//   } else {
//     setTableData(
//       rows.map((d) => {
//         if (d.paramName === data.paramName) {
//           return data;
//         }
//         return d;
//       })
//     );
//   }
// }
function handleCreateParam() {
  if (currentEditKeyRef.value) return;
  insertTableDataRecord({
    id: new Date().getTime(),
    paramName: '',
    requiredFlag: 'Y',
    paramType: 'String',
    paramDesc: '',
    editable: true,
  });
}
function handleDelete(record: Recordable) {
  const rows = getDataSource();
  setTableData(rows.filter((d) => d.paramName !== record.paramName));
}
// function testData() {
//   defHttp.get<BasicFetchResult<any>>({
//     url: `/reportDataSet/getData`,
//     params: { data_key: 'data1' },
//   });
// }
</script>
